package cn.ttxs.wq.fragment;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import cn.ttxs.lib.base.BaseFragment;
import cn.ttxs.lib.tool.ToolLog;
import cn.ttxs.wq.R;
import cn.ttxs.wq.adapter.WorkAdapter;
import cn.we.swipe.helper.WeSwipe;


public class WorkFragment extends BaseFragment implements View.OnClickListener {
    public static final String ARGS_PAGE = "args_page";
    private int mPage;
    private ImageView iv_back;
    private RecyclerView recyclerView;
    private List<String> dataList = new ArrayList<>();
    private WorkAdapter mAdapter;
    private SmartRefreshLayout refreshLayout;
    private RadioButton bt_a;
    private RadioButton bt_b;
    private RadioButton bt_c;
    private RadioButton bt_d;
    private static final int POS_A = 10;
    private static final int POS_B = 15;
    private static final int POS_C = 26;
    private static final int POS_D = 35;
    //目标项是否在最后一个可见项之后
    private boolean mShouldScroll;
    //记录目标项位置
    private int mToPosition;
    private List<RadioButton> rbList = new ArrayList<>();

    public static WorkFragment newInstance(int page) {
        ToolLog.w("page", "position:" + page);
        Bundle args = new Bundle();
        args.putInt(ARGS_PAGE, page);
        WorkFragment fragment = new WorkFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPage = getArguments().getInt(ARGS_PAGE);
    }

    @Override
    public int bindLayout() {
        return R.layout.fragment_work;
    }

    @Override
    public void initView(View view, Bundle bundle) {
        super.initView(view, bundle);
        iv_back = view.findViewById(R.id.iv_back);
        recyclerView = view.findViewById(R.id.recycle_view);
        refreshLayout = view.findViewById(R.id.refreshLayout);
        bt_a = view.findViewById(R.id.bt_a);
        bt_b = view.findViewById(R.id.bt_b);
        bt_c = view.findViewById(R.id.bt_c);
        bt_d = view.findViewById(R.id.bt_d);
        initData();
        setView();
    }


    private void initData() {
        rbList.add(bt_a);
        rbList.add(bt_b);
        rbList.add(bt_c);
        rbList.add(bt_d);
        for (int i = 0; i < 50; i++) {
            dataList.add("item" + i);
        }
        mAdapter = new WorkAdapter(getContext(), dataList);
    }

    private void setView() {
        bt_a.setOnClickListener(this);
        bt_b.setOnClickListener(this);
        bt_c.setOnClickListener(this);
        bt_d.setOnClickListener(this);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshLayout.finishRefresh(2000);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                refreshLayout.finishLoadMore(2000);
            }
        });
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        mAdapter.setDelectedItemListener(new WorkAdapter.DeletedItemListener() {
            @Override
            public void deleted(int position) {
                dataList.remove(position);
                mAdapter.notifyItemRemoved(position);
            }
        });
        recyclerView.setAdapter(mAdapter);
        WeSwipe.attach(recyclerView);
        //滚动需要的类
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (mShouldScroll && RecyclerView.SCROLL_STATE_IDLE == newState) {
                    mShouldScroll = false;
                    smoothMoveToPosition(recyclerView, mToPosition);
                } else if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    //滑动终止
                    settabbarTop();
                }
            }
        });
    }

    /**
     * 切换顶部tabbar选中状态
     */
    private void settabbarTop() {
        LinearLayoutManager ll = (LinearLayoutManager) recyclerView.getLayoutManager();
        int firstItem = ll.findFirstVisibleItemPosition();
        ToolLog.i("tzh", "----------->firstitem:" + firstItem);
        if (firstItem >= POS_D) {
            chageCheckedButton(bt_d);
        } else if (firstItem >= POS_C) {
            chageCheckedButton(bt_c);
        } else if (firstItem >= POS_B) {
            chageCheckedButton(bt_b);
        } else {
            chageCheckedButton(bt_a);
        }
    }

    private void chageCheckedButton(RadioButton rb1) {
        for (RadioButton rb : rbList) {
            if (rb == rb1) {
                rb1.setChecked(true);
            } else {
                rb.setChecked(false);
            }
        }

    }

    /**
     * 滑动到指定位置
     */
    private void smoothMoveToPosition(RecyclerView mRecyclerView, final int position) {
        // 第一个可见位置
        int firstItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(0));
        // 最后一个可见位置
        int lastItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(mRecyclerView.getChildCount() - 1));
        if (position < firstItem) {
            // 第一种可能:跳转位置在第一个可见位置之前，使用smoothScrollToPosition
            mRecyclerView.smoothScrollToPosition(position);
        } else if (position <= lastItem) {
            // 第二种可能:跳转位置在第一个可见位置之后，最后一个可见项之前
            int movePosition = position - firstItem;
            if (movePosition >= 0 && movePosition < mRecyclerView.getChildCount()) {
                int top = mRecyclerView.getChildAt(movePosition).getTop();
                // smoothScrollToPosition 不会有效果，此时调用smoothScrollBy来滑动到指定位置
                mRecyclerView.smoothScrollBy(0, top);
            }
        } else {
            // 第三种可能:跳转位置在最后可见项之后，则先调用smoothScrollToPosition将要跳转的位置滚动到可见位置
            // 再通过onScrollStateChanged控制再次调用smoothMoveToPosition，执行上一个判断中的方法
            mRecyclerView.smoothScrollToPosition(position);
            mToPosition = position;
            mShouldScroll = true;
        }
    }

    @Override
    public void doBusiness(Context mContext) {
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_a:
                smoothMoveToPosition(recyclerView, POS_A);
                chageCheckedButton(bt_a);
                break;
            case R.id.bt_b:
                smoothMoveToPosition(recyclerView, POS_B);
                chageCheckedButton(bt_b);
                break;
            case R.id.bt_c:
                smoothMoveToPosition(recyclerView, POS_C);
                chageCheckedButton(bt_c);
                break;
            case R.id.bt_d:
                smoothMoveToPosition(recyclerView, POS_D);
                chageCheckedButton(bt_d);
                break;
        }
    }
}